import { createSlice } from '@reduxjs/toolkit'
import type { UserInfoType } from './type'

const userInfoStore = createSlice({
  name: 'userInfo',
  initialState: {
    userInfo: {
      _id: '',
      phone: '',
      nick: '',
      imgUrl: '',
      token: '',
      isAdmin: false
    } as UserInfoType,
    token: '' as string
  },
  reducers: {
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    setToken(state, action) {
      state.token = action.payload
    },
    resetUserInfo(state) {
      state.userInfo = {
        _id: '',
        phone: '',
        nick: '',
        imgUrl: '',
        token: '',
        isAdmin: false
      }
    }
  }
})

// 导出userInfo的ts类型
export type UserInfoState = ReturnType<typeof userInfoStore.reducer>

// 解构出actionCreater函数
export const { setUserInfo, setToken, resetUserInfo } = userInfoStore.actions

// 导出reducer
export default userInfoStore.reducer